import { Menu, MenuProps } from 'antd';
import {
  DeleteOutlined,
  ExportOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { forwardRef } from 'react';
import styles from './styles.module.scss';
import { ModelTreeObjectType } from '@/common/types';

type Props = {
  data: ModelTreeObjectType[];
  onClick: (data: ModelTreeObjectType[], key: string) => void;
  position: {
    x: number;
    y: number;
  };
};

type MenuItem = Required<MenuProps>['items'][number];
type MenuClickEventHandler = Required<MenuProps>['onClick'];

export const ContentMenu = forwardRef<HTMLDivElement, Props>(
  ({ data, onClick, position }, ref) => {
    const menuItems: MenuItem[] = [];
    // visibility 不全部为false，则可隐藏
    if (data.some((item) => item.visibility)) {
      menuItems.push({
        key: 'hide',
        label: '隐藏',
        icon: <EyeInvisibleOutlined />,
      });
    }
    // visibility 不全为true，则可显示
    if (!data.every((item) => item.visibility)) {
      menuItems.push({
        key: 'show',
        label: '显示',
        icon: <EyeOutlined />,
      });
    }
    if (!data.every((item) => item.type === 'Folder')) {
      // type不全是Folder
      if (
        data.every(
          (item) =>
            item.type === 'Folder' ||
            item.type === 'ApproxSurface' ||
            item.type === 'Part::Feature',
        )
      ) {
        // type是Folder、ApproxSurface、Part::Feature，则可批量导出step
        menuItems.push({
          key: 'exportStep',
          label: '导出STEP',
          icon: <ExportOutlined />,
        });
      } else if (
        data.every(
          (item) =>
            item.type === 'Folder' ||
            item.type === 'MeshObject' ||
            item.type === 'PatchObject' ||
            item.type === 'CurveObject',
        )
      ) {
        // type是Folder、MeshObject、PatchObject、CurveObject，则可批量导出obj
        menuItems.push({
          key: 'exportObj',
          label: '导出OBJ',
          icon: <ExportOutlined />,
        });
      }
    }
    // 在删除菜单间加一个分割线
    if (menuItems.length > 0) {
      menuItems.push({ type: 'divider' });
    }
    // 多个或类型不是Folder，则可删除
    if (data.length > 1 || data[0]?.type !== 'Folder') {
      menuItems.push({
        key: 'delete',
        label: '删除',
        icon: <DeleteOutlined />,
      });
    }
    const handleClick: MenuClickEventHandler = (info) => {
      onClick(data, info.key);
    };
    if (menuItems.length === 0) {
      return <></>;
    }
    return (
      <div
        ref={ref}
        className={styles['context-menu']}
        style={{
          left: `${position.x}px`,
          top: `${position.y}px`,
          pointerEvents: 'auto',
        }}
        onClick={(e) => e.stopPropagation()}>
        <Menu
          onClick={handleClick}
          style={{ width: '110px', userSelect: 'none' }}
          items={menuItems}
        />
      </div>
    );
  },
);
